package com.zhouxiaoge.gitlab.commont;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author 周明阳
 * @date 2019/7/24 17:38
 */

public class GitUtil {

    private static final String gitlabName = "root";
    private static final String gitlabPassword = "root";

    /**
     * 修改.gitlab-ci.yml文件
     *
     * @param content               .gitlab-ci.yml内容
     * @param applicationGitlabPath 项目在gitlab上的地址 比如：http://localhsot:8888/root/gitlabYmlTest.git"
     */
    public static String updateGitlabYml(String content, String applicationGitlabPath) {
        if (StringUtils.isBlank(applicationGitlabPath)) {
            return "项目地址不能为空";
        }
        String gitlabUrl = applicationGitlabPath.substring(0, applicationGitlabPath.lastIndexOf("."));

        UsernamePasswordCredentialsProvider provider = new UsernamePasswordCredentialsProvider(gitlabName, gitlabPassword);
        String path = UUID.randomUUID().toString().replace("-", "");
        File file = new File("test//" + path + "//");
        try {
            Git.cloneRepository().setURI(gitlabUrl).setDirectory(file).setCredentialsProvider(provider).call();
            createYml(content, "test//" + path + "//.gitlab-ci.yml");
            Git.open(file).add().addFilepattern(".").call();
            Git.open(file).commit().setAll(true).setMessage("修改.gitlab-ci.yml " + LocalDateTime.now().toString()).call();
            Git.open(file).push().setPushAll().setForce(true).setRemote(gitlabUrl).setCredentialsProvider(provider).call();
            delFolder("test");
        } catch (GitAPIException | IOException e) {
            e.printStackTrace();
            return "修改.gitlab-ci.yml异常";
        }
        return "SUCCESS";
    }

    /**
     * 删除文件夹
     */
    private static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定文件夹下所有文件
     */
    private static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    private static void createYml(String content, String filePath) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filePath, false);
            fileWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
